package com.fms.trollalarm.custom;

import android.view.View;
import android.view.animation.Transformation;
import android.view.animation.TranslateAnimation;
import android.widget.RelativeLayout.LayoutParams;

public class MyTranslateAnimation extends TranslateAnimation {

	private View view;
	private LayoutParams params;
	private int initMarginTop;
	private int initMarginLeft;
	private float xDistance;
	private float yDistance;
	private int maxLeftMargin;
	private int maxTopMargin;

	public MyTranslateAnimation(View view, View parent, float fromXDelta,
			float toXDelta, float fromYDelta, float toYDelta) {
		super(fromXDelta, toXDelta, fromYDelta, toYDelta);
		this.view = view;
		this.params = (LayoutParams) view.getLayoutParams();
		this.initMarginLeft = params.leftMargin;
		this.initMarginTop = params.topMargin;
		this.xDistance = toXDelta - fromXDelta;
		this.yDistance = toYDelta - fromYDelta;
		this.maxLeftMargin = parent.getWidth() - view.getWidth();
		this.maxTopMargin = parent.getHeight() - view.getHeight();
	}

	@Override
	protected void applyTransformation(float interpolatedTime,
			Transformation transformation) {
		// super.applyTransformation(interpolatedTime, transformation);
		float newX = xDistance * interpolatedTime;
		float newY = yDistance * interpolatedTime;
		int newLeftMargin = initMarginLeft + (int) newX;
		int newTopMargin = initMarginTop + (int) newY;
		if ((newLeftMargin >= 0) && (newLeftMargin <= maxLeftMargin)
				&& (newTopMargin >= 0) && (newTopMargin <= maxTopMargin)) {
			params.leftMargin = newLeftMargin;
			params.topMargin = newTopMargin;
			view.requestLayout();
		} else {
			cancel();
		}
	}
}
